package com.ruoyi.vote.admin.listener;

import com.ruoyi.vote.admin.domain.vo.VoteActivityVo;
import com.ruoyi.vote.admin.service.impl.VoteActivityServiceImpl;
import com.ruoyi.vote.common.constants.VoteConstants;
import com.ruoyi.vote.admin.notice.VoteNoticeJob;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    private VoteNoticeJob voteNoticeJob;
    @Resource
    private VoteActivityServiceImpl activityService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        String aid = expiredKey.substring(expiredKey.lastIndexOf(":") + 1);
        if (expiredKey.startsWith(VoteConstants.VOTE_NOTICE_START)) {  // 活动开始通知
            VoteActivityVo voteActivity = activityService.queryById(Long.valueOf(aid));
            voteNoticeJob.voteStartNotice(voteActivity);
        }else if (expiredKey.startsWith(VoteConstants.VOTE_NOTICE_STOP)) {   // 活动结束通知
            VoteActivityVo voteActivity = activityService.queryById(Long.valueOf(aid));
            // 查询活动开始的活动
            voteNoticeJob.voteStopNotice(voteActivity);
        }
    }
}
